class GoodsCard extends HTMLElement {
  constructor() {
    super()
    const template = document.createElement('template')
    template.innerHTML = `
        <style>
          .goods-card-container {
            width: 200px;
            border: 1px solid #ddd;
          }
          .goods-img {
            width: 100%;
            height: 200px;
          }
          .goods-name {
            padding: 10px 4px;
            margin: 0;
            text-align: center;
          }
          .add-cart-btn {
            width: 100%;
          }
        </style>
        <div class="goods-card-container">
          <img class="goods-img" />
          <p class="goods-name"></p>
          <button class="add-cart-btn">加入购物车</button>
        </div>
      `
    const _shadowRoot = this.attachShadow({ mode: 'open' })
    const content = template.content.cloneNode(true)
    _shadowRoot.appendChild(content)
    this._goodsNameDom = _shadowRoot.querySelector('.goods-name')
    this._goodsImgDom = _shadowRoot.querySelector('.goods-img')
    this._button = _shadowRoot.querySelector('.add-cart-btn')
    this._button.addEventListener('click', () => {
      this.dispatchEvent(new CustomEvent('onButton', { detail: 'button' }))
    })
  }

  attributeChangedCallback(key, oldVal, newVal) {
    console.log(key, oldVal, newVal)
    this.render()
  }

  static get observedAttributes() {
    return ['img', 'name']
  }
  render() {
    this._goodsNameDom.innerHTML = this.getAttribute('name')
    this._goodsImgDom.src = this.getAttribute('img')
  }
}
customElements.define('goods-card', GoodsCard)
